package com.example.coreshopapp.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.MainActivity;
import com.example.coreshopapp.R;
import com.example.coreshopapp.adapter.PayAdapter;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.PayMethodData;
import com.example.coreshopapp.databinding.ActivityPayBinding;
import com.example.coreshopapp.keyboard.widget.CustomKeyboard;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.task.PayMethodTask;
import com.example.coreshopapp.task.PayTask;
import com.example.coreshopapp.utils.ArithUtils;
import com.example.coreshopapp.utils.LoadingUtils;
import com.example.coreshopapp.utils.SunmiPrinterHelper;
import com.example.coreshopapp.utils.TimeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bean.OrderBean;
import bean.OrderItemBean;
import dao.DaoSession;
import dao.OrderBeanDao;
import dao.OrderItemBeanDao;

public class PayActivity extends BaseActivity {
    private CustomKeyboard numKeybord;
    private ActivityPayBinding binding;
    private ArrayList<Map<String, String>> valueList;
    private List<OrderBean.PaymentListBean> payList = new ArrayList<>();
    private List<OrderItemBean> orderItemList = new ArrayList<>();
    private List<PayMethodData> payMethodData = new ArrayList<>();
    private List<Button> payButtons = new ArrayList<>();  // 用于保存所有动态创建的按钮
    // 在Activity类中添加成员变量
    private Map<String, Button> paymentIdToButtonMap = new HashMap<>();
    private OrderBean orderInfo;
    private Animation enterAnim;
    private Animation exitAnim;
    private Long mPosMemberID = new Long(0);
    private int mPaymentID = 1;
    private Double mBillAmount = 0.00;//单据总金额
    private Double mPayAll = 0.00;//已支付的总金额
    private Double mUnPayAmount = 0.00;//未支付的金额
    private boolean isSendToServer = false;//是否提交到服务器，以免重复按提交。
    private DaoSession daoSession;
    private OrderBeanDao orderBeanDao;
    private OrderItemBeanDao orderItemBeanDao;
    private PayAdapter payAdapter;
    private String orderId;
    private int payPosition = 0; // 记录当前是那条记录的支付
    private int paymentId; // 记录当前是什么支付方式
    private String scomment; // 记录当前是什么支付方式

    private SunmiPrinterHelper printerHelper;

    @SuppressLint("HandlerLeak")
    private Handler payMethodHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    payMethodData = JSON.parseArray(msg.obj.toString(), PayMethodData.class);
                    createButton(payMethodData);
                    break;
                case 9901:
                    Toast.makeText(PayActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(PayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(PayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler payHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    // 支付成功跳转订单界面,清除当前数据库的数据
                    orderBeanDao.deleteAll();
                    orderItemBeanDao.deleteAll();
                    showShortToast("下单成功");
                    orderInfo.setOrderId(msg.obj.toString());
                    if(printerHelper.isSunmiDeviceByManufacturer()) {
                    printerHelper.printOrder(orderInfo);
                    }
                    Constants.AppConstVars.MemberInfo = null;
                    gotoActivityFinish(ClassifyActivity.class);
                    break;
                case 9901:
                    Toast.makeText(PayActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(PayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(PayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };
    // 动态创建按钮
//    private void createButton(List<PayMethodData> payMethodData) {
//        getRefundPay();
//        payButtons.clear(); // 每次清空
//        binding.myLinearLayout.removeAllViews(); // 清空旧的按钮
//        new Handler().postDelayed(() -> {
//            // 分批添加，比如每批添加5个按钮
//            String ccustomerid = payMethodData.get(0).getCcustomerid();
//            paymentId = payMethodData.get(0).getPaymentId();
//            scomment = payMethodData.get(0).getScomment();
//            payMethodData.forEach(item -> {
//                // 创建按钮
//                Button myButton = new Button(this);
//                // 设置按钮属性
//                myButton.setText(item.getScomment());
//                if (ccustomerid == item.getCcustomerid()) {
//                    myButton.setTextColor(getResources().getColor(R.color.white));
//                    myButton.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                } else {
//                    myButton.setTextColor(getResources().getColor(R.color.text_color1));
//                    myButton.setBackground(getResources().getDrawable(R.drawable.button_white_bg));
//                }
//                myButton.setWidth(0);
//                myButton.setHeight(55);
//                myButton.setTextSize(14);
//                myButton.setId(View.generateViewId()); // 动态生成唯一ID（API 17+）
//                myButton.setLayoutParams(new LinearLayout.LayoutParams(
//                        0,  // 宽度为 0，配合 weight
//                        LinearLayout.LayoutParams.WRAP_CONTENT,
//                        1f  // 权重为 1，表示等分
//                ));
////            // 设置点击事件
////            myButton.setOnClickListener(v -> {
////                // 恢复所有按钮样式
////                for (Button btn : payButtons) {
////                    btn.setTextColor(getResources().getColor(R.color.text_color1));
////                    btn.setBackground(getResources().getDrawable(R.drawable.button_white_bg));
////                }
////
////                String name = myButton.getText().toString();
////                payMethodData.forEach(e -> {
////                    if (e.getScomment().equals(name) ) {
////                        paymentId = e.getPaymentId();
////                        scomment = e.getScomment();
////                    }
////                });
////                // 设置当前按钮为选中样式
////                myButton.setTextColor(getResources().getColor(R.color.white));
////                myButton.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
////                binding.idTvPayname.setText(name);
////                setDefaultAmt();
////                getRefundPay();
////            });
//                // 添加到布局中，比如添加到LinearLayout
//                myButton.setOnClickListener(v -> {
//                    Button clickedButton = (Button) v; // 当前被点击的按钮
//
//                    for (Button btn : payButtons) {
//                        btn.setTextColor(getResources().getColor(R.color.text_color1));
//                        btn.setBackground(getResources().getDrawable(R.drawable.button_white_bg));
//                    }
//
//                    String name = clickedButton.getText().toString();
//                    for (PayMethodData e : payMethodData) {
//                        if (e.getScomment().equals(name)) {
//                            paymentId = e.getPaymentId();
//                            scomment = e.getScomment();
//                            break;
//                        }
//                    }
//                    clickedButton.setTextColor(getResources().getColor(R.color.white));
//                    clickedButton.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.idTvPayname.setText(name);
//                    setDefaultAmt();
//                    getRefundPay();
//                });
//                binding.myLinearLayout.setVisibility(View.VISIBLE);
//                payButtons.add(myButton);
//                binding.myLinearLayout.addView(myButton);
//            });
//        }, 100);
//    }

    private void createButton(List<PayMethodData> payMethodData) {
        getRefundPay();
        payButtons.clear();
        binding.myLinearLayout.removeAllViews();
        paymentIdToButtonMap.clear(); // 清空映射表
        binding.idTvPayname.setText(payMethodData.get(0).getScomment());
        new Handler().postDelayed(() -> {
            String ccustomerid = payMethodData.get(0).getCcustomerid();
            paymentId = payMethodData.get(0).getPaymentId();
            scomment = payMethodData.get(0).getScomment();
            payMethodData.forEach(item -> {
                Button myButton = new Button(this);
                myButton.setText(item.getScomment());
                // 设置按钮样式
                if (paymentId == item.getPaymentId()) {
                    setButtonSelected(myButton);
                } else {
                    setButtonUnselected(myButton);
                }
                int heightInDp = 38; // 你想要的 dp 高度，比如 48dp
                int heightInPx = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP,
                        heightInDp,
                        getResources().getDisplayMetrics()
                );
                // 布局参数设置
                myButton.setWidth(0);
                myButton.setHeight(38);
                myButton.setTextSize(14);
                myButton.setId(View.generateViewId());
//                LinearLayout.LayoutParams.WRAP_CONTENT
                myButton.setLayoutParams(new LinearLayout.LayoutParams(
                        0,
                        heightInPx,
                        1f
                ));
                // 设置点击事件
                myButton.setOnClickListener(v -> {
                    selectButtonByPaymentId(item.getPaymentId() + "");
                    binding.idTvPayname.setText(item.getScomment());
                    setDefaultAmt();
                    getRefundPay();
                });
                // 元素的属性
                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                params.setMargins(8, 8, 8, 8);
                params.width = 0;
                params.height = heightInPx; // 设置高度
                params.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f); // 自动平均宽度
                binding.myLinearLayout.setVisibility(View.VISIBLE);
                payButtons.add(myButton);
                binding.myLinearLayout.addView(myButton, params);
                paymentIdToButtonMap.put(item.getPaymentId() + "", myButton); // 添加到映射表
            });
            confirmMethod();
        }, 100);
    }

    // 选中指定支付方式ID对应的按钮
    private void selectButtonByPaymentId(String paymentId) {
        // 先将所有按钮设为未选中状态
        for (Button btn : payButtons) {
            setButtonUnselected(btn);
        }
        // 找到对应ID的按钮并设为选中状态
        Button selectedButton = paymentIdToButtonMap.get(paymentId);
        if (selectedButton != null) {
            setButtonSelected(selectedButton);
            // 更新当前选中的支付方式信息
            for (PayMethodData data : payMethodData) {
                if ((data.getPaymentId() + "").equals(paymentId + "")) {
                    this.paymentId = data.getPaymentId();
                    this.scomment = data.getScomment();
                    if(payList.size() == 1) {
                        payList.get(0).setPaymentId(data.getPaymentId());
                        payList.get(0).setScomment(data.getScomment());
                        payAdapter.updatePay(payList);
                    }
                    break;
                }
            }
        }
    }

    // 设置按钮为选中状态
    private void setButtonSelected(Button button) {
        button.setTextColor(getResources().getColor(R.color.white));
        button.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
    }

    // 设置按钮为未选中状态
    private void setButtonUnselected(Button button) {
        button.setTextColor(getResources().getColor(R.color.text_color1));
        button.setBackground(getResources().getDrawable(R.drawable.button_white_bg));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //1现金，2优惠券，3聚合支付，4会员
        setContentView(R.layout.activity_pay);
        hideTopBar();
        binding = ActivityPayBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Bundle bundle = getIntent().getExtras();
        orderId = bundle.getString("orderId");
        initView();
        getRequest();
        getDao();
        printerHelper = new SunmiPrinterHelper(this);
    }

    private void getRequest() {
        getPayMethod();
    }

    private void getPayMethod() {
        LoadingUtils.showProgressDialog(PayActivity.this, "温馨提示", "加载中，请稍后");
        HashMap<String, Integer> obj = new HashMap<>();
        obj.put("isApp", 1);
        PayMethodTask payMethodTask = new PayMethodTask(obj);
        payMethodTask.setOutHandler(payMethodHandler);
        payMethodTask.execute();
    }

    private void getDao() {
        getOrderDao();
    }

    @SuppressLint("SetTextI18n")
    private void getOrderDao() {
        orderInfo = orderBeanDao.queryBuilder().where(
                OrderBeanDao.Properties.Isdel.notEq(true),
                OrderBeanDao.Properties.OrderId.eq(orderId)
        ).list().get(0);
        mBillAmount = orderInfo.getGoodsAmount();
        mUnPayAmount = orderInfo.getGoodsAmount();
        binding.idTvAmount.setText(mUnPayAmount + "");
        binding.idTxtNumber.setText(mUnPayAmount + "");
        getOrderItemDao();
        setDefaultAmt();
    }

    private void getOrderItemDao() {
        orderItemList = orderItemBeanDao.queryBuilder().where(
                OrderItemBeanDao.Properties.OrderId.eq(orderId)
        ).list();
    }

    private void initView() {
//        setSubmit("帮助");
        enterAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_in);
        exitAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_out);
        daoSession = BaseApplication.getInstance().getDaoSession(PayActivity.this);
        orderBeanDao = daoSession.getOrderBeanDao();
        orderItemBeanDao = daoSession.getOrderItemBeanDao();

        payAdapter = new PayAdapter(payList);
        payAdapter.setDeleteNewListener(onPayMethodDeleteClick);
        payAdapter.setEditNewListener(onPayMethodEditClick);
        binding.lvPaylist.setAdapter(payAdapter);


        binding.idTxtNumber.setSelectAllOnFocus(true);

        numKeybord = (CustomKeyboard) findViewById(R.id.id_numkeyboard);
        numKeybord.getLayoutBack().setOnClickListener(v -> numKeybord.startAnimation(exitAnim));
        valueList = numKeybord.getValueList();

        GridView gridView = numKeybord.getGridView();
        gridView.setOnItemClickListener(onItemClickListener);
        binding.btnAddpay.setOnClickListener(new BtnOnClickListener());
        binding.btnPayment.setOnClickListener(new BtnOnClickListener());
//        binding.btnCash.setOnClickListener(new BtnOnClickListener());
//        binding.btnMembercard.setOnClickListener(new BtnOnClickListener());
//        binding.btnBankcard.setOnClickListener(new BtnOnClickListener());
//        binding.btnAlipay.setOnClickListener(new BtnOnClickListener());
//        binding.btnWxpay.setOnClickListener(new BtnOnClickListener());
//        binding.btnCoupon.setOnClickListener(new BtnOnClickListener());
//        binding.btnOtherpay.setOnClickListener(new BtnOnClickListener());
//        binding.btnNum20.setOnClickListener(new BtnOnClickListener());
        binding.btnNum50.setOnClickListener(new BtnOnClickListener());
        binding.btnNum100.setOnClickListener(new BtnOnClickListener());
        binding.btnCancelme.setOnClickListener(new BtnOnClickListener());
        binding.editSubmit.setOnClickListener(new BtnOnClickListener());

//        binding.btnCash.setTextColor(getResources().getColor(R.color.white));
//        binding.btnCash.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));

        getRefundPay();//找零
//        setMemberCardPay();//自动转储值卡支付
        binding.idTxtNumber.addTextChangedListener(watcher);
        binding.idTxtNumber.setOnClickListener(new NumOnClickListener());
        binding.idTxtNumber.setOnFocusChangeListener(new NumOnFocusChangeListener());
    }

    // 编辑支付
    PayAdapter.PayEditClickListener onPayMethodEditClick = (i, payItem) -> {
        // 修改按钮的背景色
        binding.idTvPayname.setText(payItem.getScomment());
        binding.idTxtNumber.setText(payItem.getPayAmount() + "");
        selectButtonByPaymentId(payItem.getPaymentId() + "");
        payPosition = i;
        paymentId = payItem.getPaymentId();
        scomment = payItem.getScomment();
        setDefaultAmt();
//        confirmMethod();
//        getRefundPay();
    };
    // 删除当前支付
    PayAdapter.PayDeleteClickListener onPayMethodDeleteClick = (i, payItem) -> {
        if (payList.size() > 1) {
            // 有两个数据
            payList.remove(i);
            Log.d("delete", JSON.toJSONString(payList));
            payPosition = 0;
            paymentId = payList.get(0).getPaymentId();
            scomment = payList.get(0).getScomment();
            binding.idTvPayname.setText(payList.get(0).getScomment());
            binding.idTxtNumber.setText(payList.get(0).getPayAmount() + "");
            selectButtonByPaymentId(payList.get(0).getPaymentId() + "");
            confirmMethod();
            getRefundPay();
            setDefaultAmt();
        } else {
            // 删完就没有数据了
            payPosition = 0;
            payList.clear();
            binding.idTxtNumber.setText("");
            binding.idTvRefound.setText("0");
//            confirmMethod();
            getRefundPay();
            setDefaultAmt();
            payAdapter.updatePay(payList);
        }
    };

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
//            getRefundPay();
        }
    };

    /**
     * 计算找零
     */
    private void getRefundPay() {
        binding.idTvRefound.setText("0");
        mPayAll = 0.00;
        payList.forEach(item -> {
            mPayAll = ArithUtils.add(mPayAll, item.getPayAmount());
        });
        binding.idTvAcamount.setText(mPayAll + "");
        // 总金额小于已付金额
        if (mPayAll >= mBillAmount) {
            binding.unPayLy.setVisibility(View.GONE);
            binding.unPay.setText("0.00");
        } else {
            // 如果支付金额小于总金额显示
            binding.unPayLy.setVisibility(View.VISIBLE);
            binding.unPay.setText(JSON.toJSONString(ArithUtils.sub(mBillAmount, mPayAll)));
        }
        if (mPayAll > mBillAmount) {
            if (ArithUtils.sub(mPayAll, mBillAmount) > 100) {
                showShortToast("警告：找零大于100。");
            }
            binding.idTvRefound.setText(JSON.toJSONString(ArithUtils.sub(mPayAll, mBillAmount)));
        } else {
            binding.idTvRefound.setText("0.00");
        }
        double mUnPay = ArithUtils.sub(mBillAmount, mPayAll);
        if (mUnPay > 0) {
            mUnPayAmount = mUnPay; // 未支付的订单钱
        } else {
            mUnPayAmount = 0.0; // 未支付的订单钱
        }
    }

    // 设置editView内容
    private void setDefaultAmt() {
//        if (binding.idTxtNumber.getText().toString().length() == 0) {
//            // 未支付的余额mUnPayAmount
//            binding.idTxtNumber.setText(ArithUtils.ConvertToStrNotZero(mUnPayAmount));
//        }
        int mEnd = binding.idTxtNumber.getText().toString().length();
        binding.idTxtNumber.setSelection(mEnd); // 光标移到内容的最后一位
        binding.idTxtNumber.selectAll(); // 全选内容
    }

    // 确认支付
    private void savePosData() {
        if (isSendToServer) return;//不能重复提交
        if (payList.size() == 0) addPosPayInfo(0, "");
        if (mUnPayAmount > 0) {
            showtoast(PayActivity.this, "未支付完成，请增加。");
            return;
        }
        orderItemList.forEach(item -> {
            item.setPrice(item.getPromotionPrice() > 0 ? item.getPromotionPrice() : item.getPrice());
            item.setBn(item.getPk_material1());
            item.setSn(item.getBar_code());
        });
        // userId 是会员登录时的数据,到时候要做判断，现在没有会员
        orderInfo.setUserId(0);
        orderInfo.setPosId((int) Constants.AppConstVars.SnInfo.getFItemID());
        orderInfo.setItems(orderItemList);
        orderInfo.setClassBillNo(Constants.AppConstVars.classBillNo);
        orderInfo.setPaymentList(payList);
        orderInfo.setPayedAmount(orderInfo.getGoodsAmount()); // 总金额
        orderInfo.setPaymentTime(TimeUtils.getCurrentTime());
        orderInfo.setOrderType(11);
        orderInfo.setOrderAmount(orderInfo.getGoodsAmount());
        PayTask payTask = new PayTask(orderInfo);
        payTask.setOutHandler(payHandler);
        payTask.execute();
        LoadingUtils.showProgressDialog(PayActivity.this, "温馨提示", "加载中，请稍后");
    }

    private void setMemberPay(Double dMemberPayAmt) {
//        if (mposMember == null){
//            showShortToast("没有输入会员卡号或手机号");
//            return;
//        }
//        if (mposMember.getBalance() < dMemberPayAmt){
//            showShortToast("会员余额不足，无法支付");
//            return;
//        }
//        showLoadingDialog("正在进行会员支付，请稍候...");
//        MemberPayReq memberPayReq = new MemberPayReq();
//        memberPayReq.setAmount(dMemberPayAmt);
//        memberPayReq.setMchNo(posmaster.getFBillNo());
//        MemberPayTask memberPayTask = new MemberPayTask(mposMember,memberPayReq);
//        memberPayTask.setOutHandler(mHandler);
//        if (!memberPayTask.execute()) return;
    }


    private void setGotoBack() {
        Intent dataIntent = new Intent();
//        dataIntent.putExtra("billid", posmaster.getKInterID());
        setResult(Activity.RESULT_OK, dataIntent);
        defaultFinish();
    }

    // 添加组合
    private void addPosPayInfo(int mPayType, String sOrderNo) {
        Double payamount = 0.00;
        Double mAmount = 0.00;
        OrderBean.PaymentListBean paymentListBean = new OrderBean.PaymentListBean(this.paymentId,
                Constants.AppConstVars.classBillNo, 0, 1, 0, 0
                , orderId, this.scomment
        );
        payList.add(paymentListBean);
        payPosition = payList.size() - 1;
        binding.idTxtNumber.setText("");
        payAdapter.updatePay(payList);
    }

    /**
     * 把草稿的订单转换成有效订单
     */
//    private void setFStateCheck(PosOrderRet posorderRow){
//        PosOrderUtil posOrderTask = new PosOrderUtil();
//        if(posOrderTask.setFStateCheck(posorderRow)) {
//            setGotoBack();
//        }
//        else {
//            Toast.makeText(getActivity(), "单据不存在", Toast.LENGTH_SHORT).show();
//        }
//    }

    private class NumOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            hideAllInputMethod(PayActivity.this);
            numKeybord.setFocusable(true);
            numKeybord.setFocusableInTouchMode(true);
            numKeybord.startAnimation(enterAnim);
            numKeybord.setVisibility(View.VISIBLE);
        }
    }

    private class NumOnFocusChangeListener implements View.OnFocusChangeListener {
        public void onFocusChange(View v, boolean hasFocus) {
            try {
                if (hasFocus) {
                    hideAllInputMethod(PayActivity.this);
                    binding.idNumkeyboard.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                Log.i("错误:", e.getMessage());
            }
        }
    }

    private AdapterView.OnItemClickListener onItemClickListener = (adapterView, view, position, l) -> {
        CustomKeyboard.OnNumKeyItemClick(binding.idTxtNumber, position, valueList);
    };

    private class BtnOnClickListener implements View.OnClickListener {
        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_addpay:
                    addPosPayInfo(0, "");
                    break;
                case R.id.btn_payment:
                    savePosData();
                    break;
//                case R.id.btn_cash:
//                    setPayBtnState();
//                    mPaymentID = GlobalEnum.PaymentTag.Cash;
//                    binding.idTvPayname.setText("现金");
//                    binding.btnCash.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnCash.setTextColor(getResources().getColor(R.color.white));
//                    binding.idTxtNumber.setText(binding.idTvAcamount.getText());
//                    setDefaultAmt();
//                    getRefundPay();
//                    break;
//                case R.id.btn_membercard:
//                    if (mPosMemberID.longValue() == 0L) {
//                        CommonUtil.showMessage(PosPaymentActivity.this, "提示", "没有选择会员，不能选择储值卡付款方式。");
//                        return;
//                    }
//                    setPayBtnState();
//                    mPaymentID = GlobalEnum.PaymentTag.MemberPay;
//                    binding.idTvPayname.setText("储值卡");
//                    binding.btnMembercard.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnMembercard.setTextColor(getResources().getColor(R.color.white));
//                    setDefaultAmt();
//                    getRefundPay();
//                    break;
//                case R.id.btn_bankcard:
//                    setPayBtnState();
//                    mPaymentID = GlobalEnum.PaymentTag.BankPay;
//                    binding.idTvPayname.setText("银行卡");
//                    binding.btnBankcard.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnBankcard.setTextColor(getResources().getColor(R.color.white));
//                    setDefaultAmt();
//                    getRefundPay();
//                    break;
//                case R.id.btn_alipay:
//                    setPayBtnState();
//                    mPaymentID = GlobalEnum.PaymentTag.Mobile;
//                    binding.idTvPayname.setText("支付宝");
//                    binding.btnAlipay.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnAlipay.setTextColor(getResources().getColor(R.color.white));
//                    if (Constants.sysPara.paraRow.getFMobilePayType() > 0) setMobilePay();
//                    break;
//                case R.id.btn_wxpay:
//                    setPayBtnState();
//                   mPaymentID = GlobalEnum.PaymentTag.Mobile;
//                    binding.idTvPayname.setText("微信");
//                    binding.btnWxpay.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnWxpay.setTextColor(getResources().getColor(R.color.white));
//                    if (Constants.sysPara.paraRow.getFMobilePayType() > 0) setMobilePay();
//                    break;
//                case R.id.btn_coupon:
//                    setPayBtnState();
//                    mPaymentID = GlobalEnum.PaymentTag.Coupon;
//                    binding.idTvPayname.setText("购物券");
//                    binding.btnCoupon.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnCoupon.setTextColor(getResources().getColor(R.color.white));
//                    setDefaultAmt();
//                    getRefundPay();
//                    break;
//                case R.id.btn_otherpay:
//                    setPayBtnState();
//                    mPaymentID = GlobalEnum.PaymentTag.OtherPay;
//                    binding.idTvPayname.setText("其它");
//                    binding.btnOtherpay.setBackground(getResources().getDrawable(R.drawable.button_green1_bg));
//                    binding.btnOtherpay.setTextColor(getResources().getColor(R.color.white));
//                    setDefaultAmt();
//                    getRefundPay();
//                    break;
                case R.id.btn_num20:
                    binding.idTxtNumber.setText("20");
                    binding.idTxtNumber.setSelection(2);
                    getRefundPay();
                    break;
                case R.id.btn_num50:
                    binding.idTxtNumber.setText("50");
                    binding.idTxtNumber.setSelection(2);
                    getRefundPay();
                    break;
                case R.id.btn_num100:
                    binding.idTxtNumber.setText("100");
                    binding.idTxtNumber.setSelection(3);
                    getRefundPay();
                    break;
                case R.id.btn_cancelme:
                    setCancel();
                    break;
                case R.id.edit_submit:
                    confirmMethod();
                    break;
            }
        }
    }

    private void confirmMethod() {
        Double price = 0.00;
        // 保存当前支付
        binding.idNumkeyboard.setVisibility(View.GONE);
        if (binding.idTxtNumber.getText().toString().equals("")) {
            price = 0.00;
        } else {
            price = Double.valueOf(binding.idTxtNumber.getText().toString());
        }
        if (payList.size() < 1) {
            // 当前没有支付
            payPosition = 0;
            OrderBean.PaymentListBean paymentListBean = new OrderBean.PaymentListBean(this.paymentId,
                    Constants.AppConstVars.classBillNo, 0, 1, 0, price
                    , orderId, this.scomment
            );
            paymentListBean.setCashAmount(price);
            payList.add(paymentListBean);
        }
        payList.get(payPosition).setPayAmount(price);
        payList.get(payPosition).setCashAmount(price);
        payList.get(payPosition).setPaymentId(this.paymentId);
        payList.get(payPosition).setScomment(this.scomment);
        getRefundPay(); // 计算找零
        payAdapter.updatePay(payList);
    }


    //    private void initPrinter(){
//        switch (Constants.printSet.PrinterType){
//            case 1:
//                PrinterGp.getUsbDeviceList(this);
//                break;//佳博
//            case 2:
//                if (PrinterHs.printer == null) PrinterHs.initPrinter();
//                break;//海信打印机
//            case 3:
//                if (!PrinterXy.ISCONNECT) PrinterXy.connectUSB_Xy();
//                break;//芯华打印机
//            case 4:
//                Intent intent = new Intent();
//                intent.setPackage("woyou.aidlservice.jiuiv5");
//                intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
//                bindService(intent, PrinterSm.connService, Context.BIND_AUTO_CREATE);
//                break;//商米内置打印机
//            case 5:
//                if (UsbOperation.mPrinter == null) {
//                    UsbOperation.myOpertion = new UsbOperation(this, null);
//                    PrinterPd.getUsbDeviceList(this);
//                }
//                break;
//        }
//    }
    @Override
    public void back() {
        defaultFinish();
    }

    public void setCancel() {
        defaultFinish();
    }

//    @Override
//    public void onSubmit(View view) {
//        String msg = "1、选择支付方式，再输入支付金额，然后确认收款，按增加按钮可进行多种付款方式；";
//        msg = msg + "\n"+ "2、选择微信或支付宝，在输入框直接扫描支付码进行收款。";
//        msg = msg + "\n"+ "3、如果支付方式选错或金额输入错，可按取消或返回，再重新结算。";
//        msg = msg + "\n"+ "4、如果有移动支付和其它付款方式组合，先添加其它付款方式，最后选择微信或支付宝。";
////        CommonUtil.showContent(PosPaymentActivity.this,"帮助",msg);
//    }

//    public Handler getHandler() {
//        return mHandler;
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        switch (requestCode) {
            case 3008:
//                String payBillNo = data.getStringExtra("payBillNo");
//                int sPaymentID = data.getIntExtra("mPaymentID",GlobalEnum.PaymentTag.Mobile);
//                if (sPaymentID == GlobalEnum.PaymentTag.Mobile){
//                    mPaymentID = sPaymentID;
//                    binding.idTvPayname.setText("聚合支付");
//                }
//                if (!payBillNo.isEmpty()) addPosPayInfo(8,payBillNo);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean res = printerHelper.isSunmiDeviceByManufacturer();
        if (res) {
            printerHelper.bindPrinterService();
        }
    }
}